package com.ls.markt.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ls.markt.core.utils.DateUtils;
import com.ls.markt.model.admin.Matchs;
import com.ls.markt.service.admin.ClubService;
import com.ls.markt.service.admin.EnumManageItemService;
import com.ls.markt.service.admin.MatchService;
import com.ls.markt.util.WebResult;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/match")
public class MatchController {

    @Resource
    private MatchService matchService;

    @Resource
    private EnumManageItemService enumManageItemService;

    @Resource
    private ClubService clubService;

    @GetMapping("/index")
    public ModelAndView index(){
        return new ModelAndView("admin/match/index");
    }

    @RequestMapping("/list")
    public JSONObject list(){
        List<Matchs> matchs = matchService.listMatchs();
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (Matchs match:matchs){
            JSONObject json = (JSONObject)JSONObject.toJSON(match);
            json.put("time", DateUtils.format(match.getTime(),"yyyy-MM-dd"));
            json.put("season",enumManageItemService.getNameById(match.getSeason()));
            json.put("homeTeam",clubService.getClubName(match.getHomeTeam()));
            json.put("awayTeam",clubService.getClubName(match.getAwayTeam()));
            json.put("result",match.getHomeGoal()+":"+match.getAwayGoal());
            jsonArray.add(json);
        }
        jsonObject.put("total",matchs.size());
        jsonObject.put("rows",jsonArray);
        return jsonObject;
    }

    @GetMapping("/add")
    public ModelAndView add(){
        return new ModelAndView("admin/match/add");
    }

    @GetMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable("id")Long id, Model model){
        Matchs matchs = matchService.getMatchsById(id);
        model.addAttribute("match",matchs);
        return new ModelAndView("admin/match/edit","matchModel",model);
    }

    @PostMapping("/save")
    public JSONObject save(Matchs matchs){
        matchService.saveMatchs(matchs);
        return WebResult.success();
    }

    @PostMapping("/doDelete")
    public JSONObject doDelete(@RequestParam Long[] ids){
        matchService.removeMatchs(ids);
        return WebResult.success();
    }

}
